package net.fatcong;

import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;

public class ImageCaptureActivity extends Activity {
	
	private String imagePath;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        LinearLayout container = new LinearLayout(this);
        
        Button btn = new Button(this);
        
        btn.setHeight(20);
        btn.setWidth(100);
        
        btn.setText("capture");
        
        btn.setOnClickListener(new OnClickListener(){
        	public void onClick(View v){
        		Intent imageCaptureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//            	SD_CARD_TEMP_DIR = Environment.getExternalStorageDirectory() + File.separator + "wordpress" + File.separator + "wp-" + System.currentTimeMillis() + ".jpg";
//            	Intent takePictureFromCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//            	takePictureFromCameraIntent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(SD_CARD_TEMP_DIR)));
//            	
//            	// make sure the directory we plan to store the recording in exists
//                File directory = new File(SD_CARD_TEMP_DIR).getParentFile();
//                if (!directory.exists() && !directory.mkdirs()) {
//                  try {
//    				throw new IOException("Path to file could not be created.");
//    			} catch (IOException e) {
//    				// TODO Auto-generated catch block
//    				e.printStackTrace();
//    			}
//                }
//
//            	startActivityForResult(takePictureFromCameraIntent, 4); 
        		
        		String imageStoreFilePath = Environment.getExternalStorageDirectory() + File.separator + "fatcong" + File.separator + "pic-" + System.currentTimeMillis() + ".jpg";
        		
        		imagePath = imageStoreFilePath;
        		
        		imageCaptureIntent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(imageStoreFilePath)));
        		
        		File directory = new File(Environment.getExternalStorageDirectory() + File.separator + "fatcong");
        		
        		if(!directory.exists()){
        			directory.mkdir();
        		}
        		
        		startActivityForResult(imageCaptureIntent,0);
        		
        	}
        });
        
        container.addView(btn);
        
        setContentView(container);
    }

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		
		if(requestCode==0&&resultCode==Activity.RESULT_OK){
			
			// get the image from the path
			File file = new File(imagePath);
			
			if(file.exists()){
				byte[] fileRawBytes = new byte[(int)file.length()];
				try {
					DataInputStream dis = new DataInputStream(new FileInputStream(file));
					
					if(dis!=null){
						try {
							dis.readFully(fileRawBytes);
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				
					
				// should we create a thumbnail
				fileRawBytes = createThunmbnail(fileRawBytes, 50);
				
				Log.d("fat", ""+fileRawBytes.length);
					
				Bitmap bm = BitmapFactory.decodeByteArray(fileRawBytes, 0, fileRawBytes.length);	
				
				Log.d("fatf", ""+bm.getHeight());
				Log.d("fatf",""+bm.getWidth());
				
				
				ImageView image = new ImageView(this);
				
				image.setAdjustViewBounds(true);
				image.setMaxHeight(bm.getHeight());
				image.setMaxWidth(bm.getWidth());
				
				
				image.setImageBitmap(bm);
				
				LinearLayout container = new LinearLayout(this);
				container.addView(image);
				
				setContentView(container);
					
				} catch (FileNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			
		}
	}
	
	private byte[] createThunmbnail(byte[] srcImageBytes, int fWidth){
		
		
		
		BitmapFactory.Options options = new BitmapFactory.Options();
		
		options.inJustDecodeBounds = false;
		options.inSampleSize = 4;
		
		Bitmap bm = BitmapFactory.decodeByteArray(srcImageBytes, 0, srcImageBytes.length);
		
		int originalWidth = bm.getWidth();
		int originalHeight = bm.getHeight();
		
		Log.d("fat", ""+originalWidth);
		Log.d("fat", ""+originalHeight);
		
		
		
		int fHeight = fWidth*originalHeight/originalWidth;
		
		Log.d("fat",""+fHeight);
		
		float scale = ((float)fWidth)/originalWidth;
		
		Log.d("fat", ""+scale);
		
		Matrix m = new Matrix();
		m.postScale(scale, scale);
		
		Bitmap resized = Bitmap.createBitmap(bm, 0, 0, originalWidth, originalHeight, m, true);
		
        ByteArrayOutputStream baos = new ByteArrayOutputStream();  
        resized.compress(Bitmap.CompressFormat.JPEG, 85, baos);
        
        bm.recycle(); //free up memory
        resized.recycle();
        
        return baos.toByteArray();
		
		
	}
    
    
}